<template>
	<view class="bi-coordinate-select" :class="{'is-custom-handle': $slots.default}" @click="handleClick">
		<slot>
			<view class="bi-coordinate-select__value" v-if="hasValue">{{ showText }}</view>
			<view class="bi-coordinate-select__placeholder" v-else>{{placeholder}}</view>
		</slot>
	</view>
</template>

<script>
	import { buildUrl } from '@/utils/url.js'
	import { unique } from '@/utils/string'
	import Event from '@/utils/event.js'
	
	export default {
		name: 'BiCoordinateSelect',
		props: {
			/**
			 * {
				 lat: null,
				 lng: null,
				 address: null
			 } 
			 */
			value: {
				type: Object
			},
			editable: {
				type: Boolean,
				default: true
			},
			title: {
				type: String,
				default: '选择位置'
			},
			placeholder: {
				type: String,
				default: '请选择'
			}
		},
		data () {
			return {
				/**
				 * {
					lat: null,
					lng: null,
					address: null
				 } 
				 */
				coordinate: this.value ? Object.assign(this.value) : null
			}
		},
		computed: {
			hasValue () {
				if (!this.coordinate) {
					return false
				}
				return this.coordinate.lat && this.coordinate.lng
			},
			showText () {
				if (!this.hasValue) {
					return ''
				}
				if (this.innerValue.address) {
					return this.innerValue.address
				}
				return [this.innerValue.lng, this.innerValue.lat].join(',')
			},
			innerValue: {
				get () {
					return this.value
				},
				set (value) {
					this.$emit('input', value)
				}
			}
		},
		watch: {
			value () {
				this.coordinate = this.value ? Object.assign(this.value) : null
			}
		},
		created () {
			this.id = unique('coordinate_select_')
			Event.on(this.id, ({ coordinate }) => {
				if (coordinate) {
					this.coordinate = coordinate
					this.innerValue = {
						lat: coordinate.latitude,
						lng: coordinate.longitude,
						address: coordinate.address
					}
				} else {
					this.coordinate = null
					this.innerValue = null
				}
			})
		},
		methods: {
			handleClick () {
				const params = {
					title: this.title,
					eventName: this.id
				}
				if (this.innerValue) {
					params.lat = this.innerValue.lat
					params.lng = this.innerValue.lng
					params.address = this.innerValue.address || ''
				}
				if (this.editable) { 
					params.mode = 'pick'
				} else {
					params.mode = 'static'
				}
				uni.navigateTo({
					url: buildUrl('/packages/common/coordinate-select/coordinate-select', params)
				})
			}
		}
	}
</script>

<style lang="less">
	.bi-coordinate-select__placeholder{
		&:not(.is-custom-handle) {
			height: 24px;
			line-height: 24px;
			padding: 8px 0;
			color: #808080;
		}
	}
</style>